<template>
  <div class="lyric">
    <audio id="audio" controls preload ref="audio" :src="src"></audio>
    <div class="lyric-content" ref="lyric">
      <div class="lyric-item-wrapper">
        <div
          :class="['lyric-item', { active: activeIndex === index }]"
          v-for="(item, index) in lyricContent"
          :key="index"
          @click="lyricClick(item)"
        >
          {{ item.content }}
        </div>
      </div>
      <div class="play-btn" @click="playClick">{{ playBtnText }}</div>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";
export default {
  props: {
    src: {
      type: String,
      default() {
        return "http://m801.music.126.net/20220228202526/1395dc1b29e46e273d5241e651b4d1e5/jdymusic/obj/wo3DlMOGwrbDjj7DisKw/13211752375/c0b3/c7d4/91c5/4ecb9a9b4658c2f74414b7be2c068774.mp3";
      },
    },
    lyricContent: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      scroll: null,
      activeIndex: 0,
      playBtnText: "暂停",
    };
  },
  methods: {
    init() {
      this.$refs.audio.addEventListener("timeupdate", (e) => {
        let timeStamp = e.target.currentTime * 1000;
        this.activeIndex = this.lyricContent.findIndex((item, index) => {
          return item.ms < timeStamp && this.lyricContent[index + 1]
            ? this.lyricContent[index + 1].ms > timeStamp
            : true;
        });
        this.scroll.scrollTo(0, -27 * this.activeIndex + 54, 500);
      });
    },
    lyricScrollInit() {
      this.scroll = new BScroll(this.$refs.lyric);
      this.scroll.scrollTo(0, 54);
    },
    playClick() {
      if (this.playBtnText === "暂停") {
        this.$refs.audio.pause();
        this.playBtnText = "播放";
      } else {
        this.$refs.audio.play();
        this.playBtnText = "暂停";
      }
    },
    lyricClick(item) {
      this.$refs.audio.currentTime = item.ms / 1000;
    },
  },
  mounted() {
    this.init();
    this.lyricScrollInit();
  },
};
</script>

<style>
.lyric-content {
  position: relative;
  height: 108px;
  overflow: hidden;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  user-select: none;
}
.lyric-item {
  color: #999;
  height: 27px;
  transition: all 1s;
  cursor: pointer;
  padding-left: 1em;
}
.active {
  color: var(--color-theme);
}
.play-btn {
  position: absolute;
  right: 10px;
  top: 10px;
  color: #999;
  cursor: pointer;
  font-size: 14px;
}
</style>